// 中间件
package middleware

import (
	"errors"
	"goHelpers/app/constant"
	"goHelpers/app/error/common"
	"net/http"

	bootEntity "gitee.com/copylian/lian-go.git/entity"
	jwtHelper "gitee.com/copylian/lian-go.git/helper/jwt"

	"github.com/gin-gonic/gin"
)

// RespJson 返回参数
type RespJson struct {
	Code    int32       `json:"code"`
	Data    interface{} `json:"data"`
	Message string      `json:"message"`
}

// ParseUserWithErr 解析用户信息, 失败直接返回鉴权失败
func ParseUserWithErr() gin.HandlerFunc {
	// 返回数据
	return func(c *gin.Context) {
		jwtInfo, err := checkToken(c)
		if err != nil {
			c.JSON(http.StatusOK, RespJson{
				Code:    common.TokenCannotBeNull,
				Data:    "",
				Message: err.Error(),
			})
			c.Abort()
		}

		// 设置user_id
		c.Set("user_id", jwtInfo.Data["user_id"])
		c.Next()
	}
}

// checkToken 验证token
func checkToken(c *gin.Context) (*bootEntity.ClaimData, error) {
	// 获取头部数据
	token := c.GetHeader("token")
	if token == "" {
		return &bootEntity.ClaimData{}, errors.New(common.GetErrorMessage(common.TokenCannotBeNull))
	}

	// 本地解析jwt
	jwtInfo, err := jwtHelper.ParseToken(token, &bootEntity.JwtConfig{JwtSecret: constant.JwtSecret, JwtTTL: constant.JwtTTL})
	if err != nil || jwtInfo == nil || len(jwtInfo.Data) == 0 {
		return &bootEntity.ClaimData{}, err
	}
	return jwtInfo, err
}
